package cn.xorange.commons.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;

@Order(-5)
@Slf4j
@RestControllerAdvice
public class DataExceptionHandler {


    //@ExceptionHandler(SQLException.class)
    //public void sqlExceptionHandler(Throwable throwable){
    //    //DataException dataException =;
    //    //request.setAttribute(AttributeConstants.STATUS, dataException.getStatus());
    //    //request.setAttribute(AttributeConstants.MSG, dataException.getMessage());
    //    throw  DataException.sqlError(throwable);
    //}

    @ExceptionHandler(UnsupportedOperationException.class)
    public void unsupportedOperationException(RuntimeException e) {
        throw DataException.databaseRunException(e);
    }



    //@ExceptionHandler(java.sql.SQLIntegrityConstraintViolationException.class)
    //public void sqlIntegrityConstraintViolationException(Throwable throwable){
    //    throw DataException.sqlError(throwable);
    //}


    @ExceptionHandler(org.springframework.validation.BindException.class)
    public void bindExceptionHandle(org.springframework.validation.BindException e) {
        //Object obj = e.getModel().get(e.getObjectName());
        //Field[] fields = obj.getClass().getDeclaredFields();
        //List<FieldError> fieldErrors = e.getFieldErrors();
        //StringBuilder sb = new StringBuilder();
        //for(Field field : fields){
        //    for (FieldError error : fieldErrors){
        //        if (field.getName().equals(error.getField())){
        //            MValidate mValidate = field.getAnnotation(MValidate.class);
        //            if(Objects.nonNull(mValidate)){
        //                MColumn mColumn = field.getAnnotation(MColumn.class);
        //                if(Objects.nonNull(mColumn) && mColumn.name().isEmpty()){
        //                    sb.append(field.getName());
        //                }else {
        //                    sb.append(mColumn.name());
        //                }
        //                sb.append(error.getDefaultMessage());
        //            }else {
        //                sb.append(error.getDefaultMessage());
        //            }
        //        }
        //    }
        //}
        throw DataException.dataBandException(e.getObjectName());
    }


}
